<?php

namespace app\admin\controller\facrm\analysis;


use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;


/**
 * 业绩分析
 */
class Achievement extends Backend
{
    protected $model = null;
    protected $searchFields = 'id';
    protected $groupList=[];
    protected $childrenGroupIds;
    public function _initialize()
    {
        parent::_initialize();
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList=$groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig('groupdata', $groupdata);

        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("sourceList", $this->addon_config['source']);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }


    /**
     * 来源绩分析
     */
    public function source(){

        if ($this->request->isAjax()) {

            $contractModel = new \app\admin\model\facrm\Contract();
            $customerModel = new \app\admin\model\facrm\Customer();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_w=array();

            if (isset($filter['department_id'])) {
                if (!isset($filter['order_admin_id'])){

                    Tree::instance()->init($this->groupList);
                    $groupIds=Tree::instance()->getChildrenIds($filter['department_id'],true);
                    $authGroupList = \app\admin\model\AuthGroupAccess::
                    field('uid,group_id')
                        ->where('group_id', 'in', $groupIds)
                        ->select();
                    $owner_user_ids=array();
                    foreach ($authGroupList as $k => $v) {
                        if ($owner_user_ids&&in_array($v['uid'],$owner_user_ids)) continue;
                        $owner_user_ids[] = $v['uid'];
                    }
                    if (!$owner_user_ids){
                        $this->error("没有数据");
                    }
                    $filter_w['order_admin_id']=['in',$owner_user_ids];

                }
                unset($filter['department_id']);
                $this->request->get(['filter' => json_encode($filter)]);
            }
            //客户时间段和下单时间段
            $filter_c=array();
            if (isset($filter['order_time'])) {
                $filter['order_time'] = str_replace(' - ', ',', $filter['order_time']);
                $arr = array_slice(explode(',', $filter['order_time']), 0, 2);
                if (count($arr)==2){
                    $filter_c['collect_time'] = ['between time', $arr];
                }
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $lists = $contractModel->where('check_status', 2)->where($filter_w)
                ->field('COUNT(*) AS count, sum(money) as money, sum(return_money) as return_money,order_admin_id,source_id')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->group('source_id')->fetchSql(false)
                ->paginate();

            $j = $offset+1;

            foreach ($lists as $row) {

                //查询客户情况 兄台效率太差啊 TODO

                //分配客户数量,如果丢公海再领取就会不准
                $collect_count=$customerModel->where('source',$row->source_id)->cache(3600)
                    ->where($filter_c)
                    ->count();
                //新进客户数量
                $purchase_count=$customerModel->where('source',$row->source_id)->cache(3600)
                    ->where('deal_status',1)
                    ->where($filter_c)
                    ->count();

                $row->customer_data=array(
                    'collect_count'=>$collect_count,
                    'purchase_count'=>$purchase_count,
                    'percentage'=>number_format(($collect_count?($purchase_count/$collect_count)*100:0),2)."%",//成交率
                );
                $row['index'] = $j;
                $j++;
            }
            $result = array("total" => $lists->total(), "rows" => $lists->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 团队业绩
     */
    public function groups(){

        if ($this->request->isAjax()) {
            if ($this->request->param('ajax')) {
                return $this->getGroupAchievementEchart();
            }
            $this->tree = Tree::instance();
            $this->tree->init($this->groupList, 'pid');
            $groupList=array();
            if ($this->auth->isSuperAdmin()) {
                $groupList = $this->tree->getTreeList($this->tree->getTreeArray(0), 'name');
            } else {
                $issetIDs = array_column($this->groupList, 'id');

                $authGroupList = \app\admin\model\AuthGroup::
                field('id,name,pid')
                    ->where('id', 'in', $this->childrenGroupIds)
                    ->select();


                foreach ($authGroupList as $m => $n) {
                    if ($n['pid'] != 0) {
                        if (in_array($n['pid'], $issetIDs)) continue;
                        $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(($n['pid'])));
                        foreach ($childlist as $k => $v) {
                            $k == 0 ? $v['pid'] = 0 : '';
                            $groupList[] = $v;
                        }
                    }
                }
            }


            //时间段
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = array();
            $filter_o = array();
            if (isset($filter['order_time'])) {
                $filter['order_time'] = str_replace(' - ', ',', $filter['order_time']);
                $arr = array_slice(explode(',', $filter['order_time']), 0, 2);
                if (count($arr) == 2) {
                    $filter_o['order_time'] = $filter_c['collect_time'] = ['between time', $arr];
                }
            }


            //构造父类select列表选项数据
            $list =$groupList;

            $list = array_values($list);
            $contractModel = new \app\admin\model\facrm\Contract();
            $customerModel = new \app\admin\model\facrm\Customer();


            foreach ($list as $k => &$v) {

                $admin_ids=$this->getChildrenAdminIds($v['id']);

                //统计业绩
                $v['contract'] = $contractModel->where('check_status', 2)
                    ->field('COUNT(*) AS count, sum(money) as money, sum(return_money) as return_money,order_admin_id')
                    ->where('order_admin_id', 'in', $admin_ids)->where($filter_o)
                    ->fetchSql(false)
                    ->find();

                //分配客户数量,如果丢公海再领取就会不准
                $collect_count = $customerModel->where('owner_user_id', 'in', $admin_ids)->cache(3600)
                    ->where($filter_c)->count();
                //最近分配成交的客户数量.如果是老客户分配就会不准
                $purchase_count = $customerModel->where('owner_user_id', 'in', $admin_ids)->cache(3600)
                    ->where('deal_status', 1)->where($filter_c)->count();
                $v['customer_data'] = array(
                    'collect_count' => $collect_count,
                    'purchase_count' => $purchase_count,
                    'percentage' => number_format($collect_count ? ($purchase_count / $collect_count) * 100 : 0, 2) . "%",//成交率
                );


            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);


        }
        $erchart = [
            'achievement' => $this->getGroupAchievementEchart(false),
        ];
        $this->view->assign([
            'erchart' => $erchart,
        ]);

        return $this->view->fetch();
    }

    /**
     * 业绩分析
     * @param bool $is_ajax
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getGroupAchievementEchart($is_ajax = true)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $group_id = $this->request->param('group_id', 0, 'intval');
        $owner_user_ids=array();
        if ($owner_user_id > 0) {
            $owner_user_ids[]=$owner_user_id;
        }elseif($group_id&&$group_id>0){
            $owner_user_ids=$this->getChildrenAdminIds($group_id);
            if (!$owner_user_ids){
                $this->error("没有数据");
            }
        }
        $contractModel = new \app\admin\model\facrm\Contract();
        $data=$contractModel->getAchievementEchart($startDate,$endDate,$owner_user_ids);

        if ($is_ajax) {
            $this->success('', '', [
                'achievement' => $data
            ]);
        } else {
            return $data;
        }
    }

    /**
     * 获取子类的所有admin_ids
     * @param $group_id
     * @param bool $withself
     */
    private function getChildrenAdminIds($group_id,$withself=true){
        $owner_user_ids=array();
        Tree::instance()->init($this->groupList);
        $groupIds=Tree::instance()->getChildrenIds($group_id,$withself);

        $authGroupList = \app\admin\model\AuthGroupAccess::
        field('uid,group_id')
            ->where('group_id', 'in', $groupIds)
            ->select();

        foreach ($authGroupList as $k => $v) {
            if ($owner_user_ids&&in_array($v['uid'],$owner_user_ids)) continue;
            $owner_user_ids[] = $v['uid'];
        }
        return $owner_user_ids;
    }


}
